$(function () {

  class Login {
    constructor() {
      this.userid = $('.login_form .user_name input')
      this.userpsd = $('.login_form .user_psd input')
      this.usermsg = JSON.parse(sessionStorage.getItem('usermsg'))
      if(this.usermsg !== null){
        this.userid.val(this.usermsg.username)
        this.userpsd.val(this.usermsg.password)
      }
      this.login_btn = $('.loginsms button')
      this.msg = $('.content01 .msg')

      this.bindEvent();
    }
    bindEvent() {
      this.login_btn.on('click', () => {
        this.request();
      })
    }
    request() {
      let options = {
        url: 'http://localhost:8888/users/login',
        type: 'POST',
        headers: 'Content-Type:application/x-www-form-urlencoded',
        data: {
          username: this.userid.val(),
          password: this.userpsd.val()
        }
      }
      $.ajax(options).then(res => {
        switch (res.code) {
          case 1:
            this.success(res);
            break;
          default:
            this.err(res)
            break;
        }
      })
    }

    success(res){
      this.msg.text('登录成功');
      setTimeout(()=>{
        cookie('Token',res.token);
        cookie('ID',res.user.id.toString());
        location.href = '../../dist/index.html'

      },2000)
    }
    err(res){
      this.msg.text('登录失败，请重新输入')
      setTimeout(()=>{
        location.reload();
      },2000)
    }
  }

  new Login()
})